package com.tyut.musicdreamer.service.music.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tyut.musicdreamer.service.music.mapper.MusicMapper;
import com.tyut.musicdreamer.service.music.mapper.PlaylistMapper;
import com.tyut.musicdreamer.service.music.mapper.PlaylistMusicMapper;
import com.tyut.musicdreamer.service.music.model.dto.PlaylistCreateRequest;
import com.tyut.musicdreamer.service.music.model.entity.Music;
import com.tyut.musicdreamer.service.music.model.entity.Playlist;
import com.tyut.musicdreamer.service.music.model.entity.PlaylistMusic;
import com.tyut.musicdreamer.service.music.model.vo.MusicVO;
import com.tyut.musicdreamer.service.music.model.vo.PlaylistVO;
import com.tyut.musicdreamer.service.music.service.PlaylistService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 歌单服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PlaylistServiceImpl extends ServiceImpl<PlaylistMapper, Playlist> implements PlaylistService {

    private final PlaylistMusicMapper playlistMusicMapper;
    private final MusicMapper musicMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createPlaylist(Long userId, PlaylistCreateRequest request) {
        // 验证用户ID
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        // 创建歌单
        Playlist playlist = new Playlist();
        playlist.setUserId(userId);
        playlist.setName(request.getName());
        playlist.setDescription(request.getDescription());
        playlist.setIsPublic(request.getIsPublic());
        playlist.setSongCount(0);
        playlist.setPlayCount(0);
        playlist.setFavoriteCount(0);
        playlist.setShareCount(0);
        playlist.setCreateTime(java.time.LocalDateTime.now());
        playlist.setUpdateTime(java.time.LocalDateTime.now());
        
        // 保存歌单
        boolean success = save(playlist);
        if (!success) {
            throw new RuntimeException("创建歌单失败");
        }
        
        return playlist.getId();
    }

    @Override
    public PlaylistVO getPlaylistDetail(Long playlistId) {
        // 获取歌单信息
        Playlist playlist = getById(playlistId);
        if (playlist == null) {
            throw new RuntimeException("歌单不存在");
        }
        
        // 转换为VO
        PlaylistVO playlistVO = convertToVO(playlist);
        
        return playlistVO;
    }

    @Override
    public List<PlaylistVO> getUserPlaylists(Long userId) {
        // 查询用户创建的歌单
        LambdaQueryWrapper<Playlist> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Playlist::getUserId, userId)
                    .orderByDesc(Playlist::getCreateTime);
        
        List<Playlist> playlists = list(queryWrapper);
        
        // 转换为VO列表
        return playlists.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public Page<PlaylistVO> getPlaylistPage(Page<Playlist> page) {
        // 分页查询公开的歌单
        LambdaQueryWrapper<Playlist> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Playlist::getIsPublic, 1)
                    .orderByDesc(Playlist::getCreateTime);
        
        Page<Playlist> playlistPage = page(page, queryWrapper);
        
        // 转换为VO分页对象
        Page<PlaylistVO> voPage = new Page<>();
        voPage.setCurrent(playlistPage.getCurrent());
        voPage.setSize(playlistPage.getSize());
        voPage.setTotal(playlistPage.getTotal());
        
        List<PlaylistVO> records = playlistPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        voPage.setRecords(records);
        
        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePlaylist(Long userId, Long playlistId, PlaylistCreateRequest request) {
        // 检查歌单是否存在且属于该用户
        Playlist playlist = getById(playlistId);
        if (playlist == null) {
            throw new RuntimeException("歌单不存在");
        }
        
        if (!playlist.getUserId().equals(userId)) {
            throw new RuntimeException("无权修改此歌单");
        }
        
        // 更新歌单信息
        playlist.setName(request.getName());
        playlist.setDescription(request.getDescription());
        playlist.setIsPublic(request.getIsPublic());
        
        return updateById(playlist);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePlaylist(Long userId, Long playlistId) {
        // 检查歌单是否存在且属于该用户
        Playlist playlist = getById(playlistId);
        if (playlist == null) {
            throw new RuntimeException("歌单不存在");
        }
        
        if (!playlist.getUserId().equals(userId)) {
            throw new RuntimeException("无权删除此歌单");
        }
        
        // 删除歌单与歌曲的关联关系
        LambdaQueryWrapper<PlaylistMusic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PlaylistMusic::getPlaylistId, playlistId);
        playlistMusicMapper.delete(queryWrapper);
        
        // 删除歌单
        return removeById(playlistId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addMusicsToPlaylist(Long userId, Long playlistId, List<Long> musicIds) {
        // 检查歌单是否存在且属于该用户
        Playlist playlist = getById(playlistId);
        if (playlist == null) {
            throw new RuntimeException("歌单不存在");
        }
        
        if (!playlist.getUserId().equals(userId)) {
            throw new RuntimeException("无权修改此歌单");
        }
        
        if (musicIds == null || musicIds.isEmpty()) {
            return 0;
        }
        
        // 检查歌曲是否已在歌单中
        LambdaQueryWrapper<PlaylistMusic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PlaylistMusic::getPlaylistId, playlistId)
                    .in(PlaylistMusic::getMusicId, musicIds);
        List<PlaylistMusic> existingRelations = playlistMusicMapper.selectList(queryWrapper);
        
        // 过滤掉已存在的歌曲
        List<Long> existingMusicIds = existingRelations.stream()
                .map(PlaylistMusic::getMusicId)
                .collect(Collectors.toList());
        
        List<Long> newMusicIds = musicIds.stream()
                .filter(id -> !existingMusicIds.contains(id))
                .collect(Collectors.toList());
        
        if (newMusicIds.isEmpty()) {
            return 0;
        }
        
        // 获取当前歌单最大的排序序号
        Integer maxSortOrder = 0;
        if (!existingRelations.isEmpty()) {
            maxSortOrder = existingRelations.stream()
                    .mapToInt(PlaylistMusic::getSortOrder)
                    .max()
                    .orElse(0);
        }
        
        // 批量添加歌曲到歌单
        List<PlaylistMusic> relations = new ArrayList<>();
        for (int i = 0; i < newMusicIds.size(); i++) {
            PlaylistMusic relation = new PlaylistMusic();
            relation.setPlaylistId(playlistId);
            relation.setMusicId(newMusicIds.get(i));
            relation.setSortOrder(maxSortOrder + i + 1);
            relations.add(relation);
        }
        
        // 批量保存
        int addedCount = 0;
        for (PlaylistMusic relation : relations) {
            playlistMusicMapper.insert(relation);
            addedCount++;
        }
        
        // 更新歌单中的歌曲数量
        if (addedCount > 0) {
            playlist.setSongCount(playlist.getSongCount() + addedCount);
            updateById(playlist);
        }
        
        return addedCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeMusicsFromPlaylist(Long userId, Long playlistId, List<Long> musicIds) {
        // 检查歌单是否存在且属于该用户
        Playlist playlist = getById(playlistId);
        if (playlist == null) {
            throw new RuntimeException("歌单不存在");
        }
        
        if (!playlist.getUserId().equals(userId)) {
            throw new RuntimeException("无权修改此歌单");
        }
        
        if (musicIds == null || musicIds.isEmpty()) {
            return 0;
        }
        
        // 删除关联关系
        LambdaQueryWrapper<PlaylistMusic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PlaylistMusic::getPlaylistId, playlistId)
                    .in(PlaylistMusic::getMusicId, musicIds);
        
        int deletedCount = playlistMusicMapper.delete(queryWrapper);
        
        // 更新歌单中的歌曲数量
        if (deletedCount > 0) {
            playlist.setSongCount(Math.max(0, playlist.getSongCount() - deletedCount));
            updateById(playlist);
        }
        
        return deletedCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePlaylistCover(Long userId, Long playlistId, String coverUrl) {
        // 检查歌单是否存在且属于该用户
        Playlist playlist = getById(playlistId);
        if (playlist == null) {
            throw new RuntimeException("歌单不存在");
        }
        
        if (!playlist.getUserId().equals(userId)) {
            throw new RuntimeException("无权修改此歌单");
        }
        
        // 更新封面
        playlist.setCoverUrl(coverUrl);
        
        return updateById(playlist);
    }

    @Override
    public List<MusicVO> getPlaylistMusics(Long playlistId) {
        // 验证歌单是否存在
        Playlist playlist = getById(playlistId);
        if (playlist == null) {
            throw new RuntimeException("歌单不存在");
        }
        
        // 查询歌单中的歌曲关联
        LambdaQueryWrapper<PlaylistMusic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PlaylistMusic::getPlaylistId, playlistId)
                   .orderByAsc(PlaylistMusic::getSortOrder);
        List<PlaylistMusic> playlistMusics = playlistMusicMapper.selectList(queryWrapper);
        
        if (playlistMusics.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取所有音乐ID
        List<Long> musicIds = playlistMusics.stream()
                .map(PlaylistMusic::getMusicId)
                .collect(Collectors.toList());
        
        // 查询音乐信息
        List<Music> musics = musicMapper.selectBatchIds(musicIds);
        
        // 转换为VO
        List<MusicVO> musicVOs = musics.stream()
                .map(this::convertToMusicVO)
                .collect(Collectors.toList());
        
        // 按照歌单中的排序顺序重新排序
        Map<Long, Integer> orderMap = playlistMusics.stream()
                .collect(Collectors.toMap(
                    PlaylistMusic::getMusicId,
                    PlaylistMusic::getSortOrder,
                    (a, b) -> a // 如果有重复的key，保留第一个
                ));
        
        musicVOs.sort((a, b) -> {
            Integer orderA = orderMap.getOrDefault(Long.valueOf(a.getId()), Integer.MAX_VALUE);
            Integer orderB = orderMap.getOrDefault(Long.valueOf(b.getId()), Integer.MAX_VALUE);
            return orderA.compareTo(orderB);
        });
        
        return musicVOs;
    }

    /**
     * 将实体转换为VO
     */
    private PlaylistVO convertToVO(Playlist playlist) {
        PlaylistVO vo = new PlaylistVO();
        BeanUtils.copyProperties(playlist, vo);
        
        // 设置默认的创建者信息
        vo.setUsername("用户" + playlist.getUserId());
        vo.setUserAvatar("https://api.dicebear.com/7.x/avataaars/svg?seed=user" + playlist.getUserId());
        
        return vo;
    }
    
    /**
     * 将音乐实体转换为VO
     */
    private MusicVO convertToMusicVO(Music music) {
        MusicVO vo = new MusicVO();
        BeanUtils.copyProperties(music, vo);
        
        // 设置标签数组
        if (music.getTags() != null && !music.getTags().isEmpty()) {
            vo.setTagArray(music.getTags().split(","));
        }
        
        // 设置默认的创作者信息
        vo.setCreatorName("用户" + music.getCreatorId());
        vo.setCreatorAvatar("https://api.dicebear.com/7.x/avataaars/svg?seed=user" + music.getCreatorId());
        
        return vo;
    }
} 